using AutoMapper;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructrue.Interfaces;
using BaseData.ReadApi.Application.Command.Roles;
using BaseData.ReadApi.Dto;
using MediatR;

namespace BaseData.ReadApi.Application.CommandHandler.Roles
{
    /// <summary>
    /// 处理获取角色详情命令的处理器
    /// </summary>
    public class GetRoleDetailCommandHandler : IRequestHandler<GetRoleDetailCommand, Apiresult<RoleDetailOutput>>
    {
        private readonly IBasepository<UserInfo> userpository;  // 用户信息仓储接口
        private readonly IBasepository<Role> rolepository;  // 角色仓储接口
        private readonly IBasepository<UserRole> uRpository;  // 用户角色仓储接口
        private readonly IBasepository<Permission> permisspository;  // 权限仓储接口
        private readonly IBasepository<RolePermiss> rolePerpository;  // 角色权限仓储接口
        private readonly IMapper mapper;  // 对象映射器
        private readonly ILogger<GetRoleDetailCommandHandler> logger;  // 日志记录器

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="_userpository">用户信息仓储</param>
        /// <param name="_rolepository">角色仓储</param>
        /// <param name="_URpository">用户角色仓储</param>
        /// <param name="_permisspository">权限仓储</param>
        /// <param name="_rolePerpository">角色权限仓储</param>
        /// <param name="_mapper">对象映射器</param>
        /// <param name="_logger">日志记录器</param>
        public GetRoleDetailCommandHandler(
            IBasepository<UserInfo> _userpository,
            IBasepository<Role> _rolepository,
            IBasepository<UserRole> _URpository,
            IBasepository<Permission> _permisspository,
            IBasepository<RolePermiss> _rolePerpository,
            IMapper _mapper,
            ILogger<GetRoleDetailCommandHandler> _logger)
        {
            userpository = _userpository;
            rolepository = _rolepository;
            uRpository = _URpository;
            permisspository = _permisspository;
            rolePerpository = _rolePerpository;
            mapper = _mapper;
            logger = _logger;
        }

        /// <summary>
        /// 处理获取角色详情命令
        /// </summary>
        /// <param name="request">获取角色详情的请求数据</param>
        /// <param name="cancellationToken">取消标记</param>
        /// <returns>返回角色详情结果</returns>
        public async Task<Apiresult<RoleDetailOutput>> Handle(GetRoleDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查找角色信息
                var role = await rolepository.GetModel(r => r.RoleId == request.RoleId);
                if (role == null)
                {
                    return new Apiresult<RoleDetailOutput>
                    {
                        Code = ResultCode.查询失败,
                        Message = "角色不存在"
                    };
                }

                // 创建角色详情输出对象
                var result = mapper.Map<RoleDetailOutput>(role);

                // 获取角色权限信息
                var rolePermission = await rolePerpository.GetModel(rp => rp.RoleId == request.RoleId);
                if (rolePermission != null)
                {
                    // 获取权限信息
                    var permission = await permisspository.GetModel(p => p.PermissionId == rolePermission.PermissionId);
                    if (permission != null)
                    {
                        result.PermissionId = permission.PermissionId;
                        result.PermissionName = permission.PermissionName ?? string.Empty;
                    }
                }

                // 统计该角色的用户数量
                var userCount = uRpository.GetAll().Count(ur => ur.RoleId == request.RoleId);
                result.UserCount = userCount;

                return new Apiresult<RoleDetailOutput>
                {
                    Code = ResultCode.查询成功,
                    Result = result
                };
            }
            catch (Exception ex)
            {
                // 记录日志
                logger.LogError($"GetRoleDetailCommandHandler.Handle方法异常：{ex.Message},{ex.StackTrace}");
                return new Apiresult<RoleDetailOutput>
                {
                    Code = ResultCode.查询失败,
                    Message = "系统异常，获取角色详情失败"
                };
            }
        }
    }
}